#include "rnet.h"
#include "rlock.h"
#include "server_service.h"
#include "server_task.h"
#include "server_loop_task.h"

string gs_server_ip = "120.26.120.105";
short gsh_server_port = 9001;

server_service::server_service() 
{
	pthread_mutex_init(&m_task.m_lock, NULL) ;
}

server_service::~server_service( ) 
{
	pthread_mutex_destroy(&m_task.m_lock) ;
	m_task.clear();
}

bool server_service::start(void)
{
	rthreadpool::_instance().add_task(new server_task(m_task)) ;
	rthreadpool::_instance().add_task(new server_loop_task()) ;
	
	return true ;
}

bool server_service::connect()
{
	rmutex rlock(m_task.m_lock);
			
	if ( m_task.mi_fd != -1 )
	{
		//rlog << "server(" << gs_server_ip  << ":" << gsh_server_port << ") already connected" << endl ;
		return true ;
	}

	if( rnet::connect( m_task.mi_fd, gs_server_ip, gsh_server_port ) )
	{
		rlog << "connect server(" << gs_server_ip << ":" << gsh_server_port << ") success" << endl;
		return true ;
	}
	
	rlog << "connect server(" << gs_server_ip << ":" << gsh_server_port << ") error" << endl;

	if ( m_task.mi_fd != -1 )
	{
		rlog << "close(" << m_task.mi_fd << ")" << endl;
		m_task.clear();
	}

	sleep(2);
	
	return false ;
}

bool server_service::write(const string& s_data)
{
	if ( !connect() )
		return false ;
	
	rmutex rlock(m_task.m_lock);

	if( rjson::write( m_task.mi_fd, s_data ) < 0 )
	{
		rlog << "json::write server(" << m_task.mi_fd << ") error" << endl ;
		return false ;
	}

	rlog << "write server(" << m_task.mi_fd << ") data" << endl << s_data << endl ;
	
	return true ;
}

